<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="用户名" prop="userName">
                <el-input
                    v-model="queryParams.userName"
                    placeholder="请输入用户名"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input
                    v-model="queryParams.phone"
                    placeholder="请输入电话"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="区域位置" prop="area">
                <el-input
                    v-model="queryParams.area"
                    placeholder="请输入区域位置,多个区域请用,号分割"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="最低价" prop="minPrice">
                <el-input
                    v-model="queryParams.minPrice"
                    placeholder="请输入最低价"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="最高价" prop="maxPrice">
                <el-input
                    v-model="queryParams.maxPrice"
                    placeholder="请输入最高价"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="创建时间" prop="createDate">
                <el-date-picker clearable
                                v-model="queryParams.createDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择创建时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['admin:business:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['admin:business:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['admin:business:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['admin:business:export']"
                >导出
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-view"
                    size="mini"
                    @click="changeShowPhone"
                > {{ this.show_phone ? '隐藏号码' : '查看号码' }}
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="businessList" @selection-change="handleSelectionChange" height="680">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="用户名" align="left" prop="userName"/>
            <el-table-column label="电话" align="center" prop="phone" :formatter="formatPhone"/>
            <el-table-column label="区域位置" align="center" prop="area"/>
            <el-table-column label="最低价" align="center" prop="minPrice"/>
            <el-table-column label="最高价" align="center" prop="maxPrice"/>
            <el-table-column label="匹配房源" align="center" prop="maxPrice">
                <template slot-scope="scope">
                    <el-button plain @click.native.prevent="getDialogList(scope.$index, scope.row)" size="mini">
                        {{ scope.row.matchCount }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="经纪人" align="center" prop="owner"/>
            <el-table-column label="创建时间" align="center" prop="createDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['admin:business:edit']"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['admin:business:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改业务需求对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="form.userName" placeholder="请输入用户名"/>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入电话"/>
                </el-form-item>
                <el-form-item label="区域位置" prop="area">
                    <el-input v-model="form.area" placeholder="请输入区域位置" @input="handleAreaInput"/>
                </el-form-item>
                <el-form-item label="最低价(万)" prop="minPrice">
                    <el-input v-model="form.minPrice" placeholder="请输入最低价"/>
                </el-form-item>
                <el-form-item label="最高价(万)" prop="maxPrice">
                    <el-input v-model="form.maxPrice" placeholder="请输入最高价"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 房源详情 -->
        <el-dialog :visible.sync="matchDialog" width="80%" append-to-body>
            <template slot="title">
                <span>{{'客户:【'+currRow.userName+'】匹配信息'}}</span>
            </template>
            <el-row class="mb8" style="text-align: right">
                <el-switch size="small" v-model="dialogQueryParams.isHistory" @change="changeHistorySwitch" active-text="查看历史" inactive-text=""></el-switch>
            </el-row>
            <el-table v-loading="loading" :data="tbDataList">
                <el-table-column label="标题" align="left" header-align="center" prop="title" width="280"/>
                <el-table-column label="状态" align="center" prop="status">
                    <template v-slot="scope">
                        <el-tag size="small" effect="plain" :type="getStatusLayout(scope.row.status)">
                            {{ getStatusText(scope.row, scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="预览" align="center" prop="picUrl">
                    <template #default="{row}">
                        <el-image style="width: 50px; height: 50px" :src="row.picUrl" :preview-src-list="[row.picUrl]"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="起拍价" align="center" prop="initialPrice" :formatter="formatPrice"/>
                <el-table-column label="当前价" align="center" prop="currentPrice" :formatter="formatPrice"/>
                <el-table-column label="评估价" align="center" prop="consultPrice" :formatter="formatPrice"/>
                <el-table-column label="市场价" align="center" prop="marketPrice" :formatter="formatPrice"/>
                <el-table-column label="起拍时间" align="center" prop="start">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.start, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="结束时间" align="center" prop="end">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.end, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="距开始" align="center" prop="timeToStart">
                    <template slot-scope="scope" v-if="formatTimeCountdown(scope.row, scope.row.timeToStart)>0">
                        <el-statistic size="small" format="DD天HH时mm分ss秒" :value="formatTimeCountdown(scope.row, scope.row.timeToStart)" time-indices>
                        </el-statistic>
                    </template>
                </el-table-column>
                <el-table-column label="距结束" align="center" prop="timeToEnd">
                    <template slot-scope="scope">
                        <el-statistic v-if="formatTimeCountdown(scope.row, scope.row.timeToEnd)>0" size="small" format="DD天HH时mm分ss秒" :value="formatTimeCountdown(scope.row, scope.row.timeToEnd)" time-indices>
                        </el-statistic>
                        <el-tag v-else size="small" type="info" effect="plain">已结束</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="围观次数" align="center" prop="viewerCount" />
                <el-table-column label="延迟次数" align="center" prop="delayCount" />
                <el-table-column label="商品详情" align="center" prop="itemUrl">
                    <template v-slot="scope">
                        <el-link type="primary" :underline="false" :href="'https://'+scope.row.itemUrl" target="_blank">详情</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                v-show="dialogTotal>0"
                :total="dialogTotal"
                :page.sync="dialogQueryParams.pageNum"
                :limit.sync="dialogQueryParams.pageSize"
                @pagination="getDialogList"
            />
        </el-dialog>
    </div>
</template>

<script>
import {
    listBusiness,
    getBusiness,
    delBusiness,
    addBusiness,
    updateBusiness,
    listBusinessDetail, listTbData
} from "@/api/admin/business"
import Cookies from "js-cookie";

export default {
    name: "Business",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 弹出层总条数
            dialogTotal: 0,
            // 业务需求表格数据
            businessList: [],
            // 淘宝房源表格数据
            tbDataList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userName: null,
                phone: null,
                area: null,
                minPrice: null,
                maxPrice: null,
                createDate: null
            },
            // 弹出框查询参数
            dialogQueryParams:{
                pageNum: 1,
                pageSize: 10,
                isHistory: false
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            // dialog匹配房源弹出框
            matchDialog: false,
            // 点击当前的行
            currRow: {},
            // 是否显示电话号码
            show_phone: false
        }
    },
    created() {
        this.getList()
    },
    methods: {
        // 处理区域输入的内容 限制中文逗号的出现
        // 1. 把中文逗号统一换成英文逗号
        // 2. 去掉连续多个逗号
        handleAreaInput(val){
            this.form.area = val
                .replace(/，/g, ',')        // 中文→英文
                .replace(/\s+/g, '')       // 移除所有空格（全角/半角）
                .replace(/,{2,}/g, ',')    // 避免出现“,,”
        },
        changeShowPhone(){
            if(!this.show_phone){
                this.$prompt('', '校验', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputType: 'password',
                    inputPlaceholder: '请输入密码',
                    inputValidator: val => val ? true : '密码不能为空'
                }).then(({ value }) => {
                    const password = this.$cache.local.get('validPwd')
                    if(value === password){
                        this.show_phone = true
                        this.$message({type: 'success', message: '校验通过!'})
                    }else{
                        this.$message({type: 'warning', message: '校验失败!'})
                    }
                }).catch(() => {
                    this.$message({type: 'info', message: '取消输入'});
                });
            }else{
                this.show_phone = false
            }

        },
        changeHistorySwitch(){
            listTbData(this.dialogQueryParams).then(res => {
                this.tbDataList = res.rows;
                this.dialogTotal = res.total
            })
        },
        /** 显示匹配房源弹出层 */
        getDialogList(idx, row){
            if(row?.id){
                this.currRow = row;
            }
            this.dialogQueryParams.id = this.currRow.id
            listTbData(this.dialogQueryParams).then(res => {
                this.tbDataList = res.rows;
                this.dialogTotal = res.total
                this.matchDialog = true
            })
        },
        /** 查询业务需求列表 */
        getList() {
            this.loading = true
            listBusiness(this.queryParams).then(response => {
                this.businessList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                userName: null,
                phone: null,
                area: null,
                minPrice: null,
                maxPrice: null,
                createDate: null
            }
            this.resetForm("form")
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm")
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = "添加业务需求"
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getBusiness(id).then(response => {
                this.form = response.data
                this.form.phone = this.formatPhone(undefined, undefined, this.form.phone)
                this.open = true
                this.title = "修改业务需求"
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        if(this.form.phone && this.form.phone.indexOf("*") != -1){
                            this.form.phone = undefined
                        }
                        updateBusiness(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功")
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addBusiness(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功")
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除业务需求编号为"' + ids + '"的数据项？').then(function () {
                return delBusiness(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => {
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('admin/business/export', {
                ...this.queryParams
            }, `business_${new Date().getTime()}.xlsx`)
        },
        getStatusText(row, val){
            let millSeconds = this.formatTimeCountdown(row, row.timeToEnd)
            if(millSeconds <= 0){
                val = 'end'
                row.status = 'end'
            }
            switch(val){
                case 'doing':
                {
                    val = '正在进行'
                    break;
                }
                case 'todo':
                {
                    val = '即将开始'
                    break;
                }
                case 'end':
                {
                    val = '已结束'
                    break;
                }
                default :
                    val = '未知'
            }
            return val
        },
        getStatusLayout(val){
            switch(val){
                case 'doing':
                {
                    val = 'danger'
                    break;
                }
                case 'todo':
                {
                    val = 'success'
                    break;
                }
                default :
                    val = 'info'
            }
            return val
        },
        /** 手机号码脱敏 */
        formatPhone(row, col, cellvalue){
            if(!this.show_phone && cellvalue){
                return cellvalue.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
            }else{
                return cellvalue
            }
        },
        formatPrice(row, col, cellValue){
            if(!cellValue) return ""
            return (cellValue / 10000).toFixed(2) + '万'
        },
        formatTimeCountdown(row, cellValue){
            if(cellValue <= 0) return ''
            let endDate = new Date(row.end);
            endDate.setHours(10)
            let today = new Date();
            let diff = endDate - today
            if(diff > 0){
                cellValue = endDate
            }else{
                cellValue = 0
            }
            /*if(diff > 0){
                // 计算剩余天数
                let day = diff / (1000 * 60 * 60 * 24)
                diff %= (1000 * 60 * 60 * 24)
                // 计算小时数
                let hours = diff / (1000 * 60 * 60)
                diff %= (1000 * 60 * 60)
                // 计算分钟数
                let minutes = diff / (1000 * 60)
                diff %= 1000
                // 计算秒数
                let second = diff / 1000
                console.log(`${day}天 ${hours}时 ${minutes}分 ${second}秒`)
            }*/
            return cellValue
        }
    }
}
</script>
<style>
    .el-statistic .con .number{
        font-size: 12px !important
    }
</style>
